1、转存并清理 15 天前的日志
#!/bin/bash

# 设置日志保留天数
DAYS_TO_KEEP=15
LOG_DIR="/var/lib/docker/containers"
BACKUP_DIR="/var/log/docker_backups"
TIMESTAMP=$(date +%Y%m%d%H%M%S)

# 创建备份目录
mkdir -p "$BACKUP_DIR"

# 遍历所有容器日志
for container_id in $(docker ps -aq); do
    LOG_FILE="$LOG_DIR/$container_id/${container_id}-json.log"
    BACKUP_FILE="$BACKUP_DIR/${container_id}-${TIMESTAMP}.log"

    # 检查日志文件是否存在
    if [ -f "$LOG_FILE" ]; then
        echo "Backing up logs for container: $container_id"

        # 转存日志
        cp "$LOG_FILE" "$BACKUP_FILE"
        gzip "$BACKUP_FILE"  # 压缩备份文件

        # 清理 15 天前的日志
        echo "Cleaning logs older than $DAYS_TO_KEEP days for container: $container_id"
        find "$LOG_DIR/$container_id" -name "*.log" -type f -mtime +$DAYS_TO_KEEP -exec rm -f {} \;
    else
        echo "No log file found for container: $container_id"
    fi
done

echo "Log backup and cleanup completed!"

2、部署脚本
#!/bin/bash
SERVICE_NAME="docker.service"

# 检查并创建目录的函数
check_and_create_dir() {
    local dir_path=$1
    if [ -d "$dir_path" ]; then
        echo "目录 $dir_path 已存在"
    else
        echo "目录 $dir_path 不存在，正在创建..."
        mkdir -p "$dir_path"
        if [ $? -eq 0 ]; then
            echo "目录 $dir_path 创建成功"
        else
            echo "目录 $dir_path 创建失败" >&2
            exit 1
        fi
    fi
}

# 检查当前值
current=$(cat /proc/sys/net/ipv4/ip_forward)
if [ "$current" -eq 1 ]; then
    echo "net.ipv4.ip_forward is already 1."
    exit 0
fi

# 立即设置当前值为1
sudo sysctl -w net.ipv4.ip_forward=1 >/dev/null

# 确保配置文件正确
if grep -q "^net.ipv4.ip_forward[[:space:]]*=" /etc/sysctl.conf; then
    # 存在则替换为1
    sudo sed -i 's/^\(net.ipv4.ip_forward[[:space:]]*=\).*/\1 1/' /etc/sysctl.conf
else
    # 不存在则追加
    echo "net.ipv4.ip_forward = 1" | sudo tee -a /etc/sysctl.conf >/dev/null
fi

# 输出成功信息
echo "Successfully set net.ipv4.ip_forward to 1 (persistent)."

# 检查并创建/etc/docker目录
check_and_create_dir "/etc/docker"
check_and_create_dir "/data/docker/docker"

echo "Start to install es-docker!"
# Check if the tarball exists and is non-empty
if [ -s "docker-20.10.9.tgz" ]; then
    echo "step 01: unzip docker file"
    tar -zxvf docker-20.10.9.tgz
else
    echo "docker-20.10.9.tgz does not exist or is empty!"
    exit 1
fi

echo -e "\n"
# Check if the directory exists
if [ -d "docker" ]; then
    echo "step 02: Configuration container file"
    cp -R docker/* /usr/bin/
    cp docker.service /usr/lib/systemd/system/
    cp daemon.json /etc/docker/
    systemctl daemon-reload
    echo "docker copy done"
fi

echo -e "\n"
# Check if the service file was copied successfully
if [ -f "/usr/lib/systemd/system/docker.service" ]; then
    echo "step 03: start container service"
    systemctl restart docker && systemctl enable docker.service
    echo "docker is success!"
else
    echo "docker.service writing failed!"
    exit 1
fi

echo -e "\n"
# Check if the docker-compose binary exists
if [ -f "docker-compose-linux-x86_64" ]; then
    echo "step 04: configuration docker-compose service:"
    cp docker-compose-linux-x86_64 /usr/bin/docker-compose
    chmod +x /usr/bin/docker-compose
    echo "docker-compose is success!"
else
    echo "docker-compose installation failed!"
    exit 1
fi

#daemon.json




3、清理脚本
#sudo find /data/basic-service/docker-log-bak/ -type d -mtime +7 -exec rm -rf {} \;
#sudo find /data/docker/docker/containers/ -name "*-json.log" -exec ls -l {} \;
echo "0 2 * * 6,0  root  cd /data/basic-service && sh clean-docker-log.sh" >>  /etc/crontab

#!/bin/bash
# 清理 Docker 容器日志并按容器备份到指定目录（支持详细日志和错误处理）

# 全局变量
LOG_DIR="/data/docker/docker/containers"
BACKUP_ROOT="/data/basic-service/docker-log-bak"
LOG_FILE="/data/basic-service/clean.log"
TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S")
BACKUP_DIR="$BACKUP_ROOT/$TIMESTAMP"

# 日志记录函数（带颜色和时间戳）
log_message() {
    local LEVEL="$1"
    local MSG="$2"
    local COLOR=""
    case "$LEVEL" in
        INFO)  COLOR="\033[34m" ;;  # 蓝色
        WARN)  COLOR="\033[33m" ;;  # 黄色
        ERROR) COLOR="\033[31m" ;;  # 红色
        *)     COLOR="\033[0m"  ;;  # 默认
    esac
    echo -e "[$(date "+%Y-%m-%d %H:%M:%S")] $COLOR$LEVEL: $MSG\033[0m" | tee -a "$LOG_FILE"
}

# 创建备份目录
create_backup_dir() {
    if [ ! -d "$BACKUP_DIR" ]; then
        mkdir -p "$BACKUP_DIR" || {
            log_message "ERROR" "创建备份目录失败：$BACKUP_DIR"
            exit 1
        }
        log_message "INFO" "成功创建备份目录：$BACKUP_DIR"
    fi
}

# 备份并清理单个日志文件
backup_and_clean_log() {
    local LOG_FILE="$1"
    local CONTAINER_ID=$(basename "$(dirname "$LOG_FILE")")
    local LOG_NAME=$(basename "$LOG_FILE")
    local BACKUP_PATH="$BACKUP_DIR/$CONTAINER_ID-$LOG_NAME"

    # 备份日志文件
    cp "$LOG_FILE" "$BACKUP_PATH" 2>/dev/null
    if [ $? -eq 0 ]; then
        log_message "INFO" "备份成功：$LOG_FILE → $BACKUP_PATH"
    else
        log_message "ERROR" "备份失败：$LOG_FILE"
    fi

    # 清空原始日志文件
    truncate -s 0 "$LOG_FILE" 2>/dev/null
    if [ $? -eq 0 ]; then
        log_message "INFO" "清空成功：$LOG_FILE"
    else
        log_message "ERROR" "清空失败：$LOG_FILE"
    fi
}

# 主清理函数
clean_logs() {
    create_backup_dir

    # 查找所有容器日志文件（包含分割后的日志文件）
    logs=$(find "/data/docker/docker/containers/" -type f \( -name '*-json.log' -o -name '*-json.log.*' \))

    if [ -z "$logs" ]; then
        log_message "WARN" "未找到任何容器日志文件！"
        return
    fi

    log_message "INFO" "开始清理 Docker 容器日志..."
    for log in $logs; do
        if [ -f "$log" ]; then
            backup_and_clean_log "$log"
        else
            log_message "WARN" "文件不存在：$log"
        fi
    done
    log_message "INFO" "日志清理完成！备份路径：$BACKUP_DIR"
}

# 主函数
main() {
    log_message "INFO" "--------------------------"
    log_message "INFO" "开始执行日志清理任务"
    clean_logs
    log_message "INFO" "任务结束"
    log_message "INFO" "--------------------------"
}

main
